#include "logui.h"
#include "ui_logui.h"

logui::logui(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::logui)
{
    ui->setupUi(this);


    this->setFixedSize(this->size());//锁定窗口大小

    if(ini() == false){//如果初始化数据库失败
        QMessageBox::warning(0,"警告","初始化数据库失败!");
        return;
    }
}

logui::~logui()
{
    delete ui;
}

void logui::on_btnLog_clicked()
{
    m_role = ROLE::ADMIN;//默认登陆的是管理员用户

    QString account = ui->editAccount->text();
    QString pswd = ui->editPswd->text();
    if(account.simplified().isEmpty()){//如果账号为空
        QMessageBox::information(0,"提示","账号不能为空.");
        return;
    }
    if(pswd.simplified().isEmpty()){//如果密码为空
        QMessageBox::information(0,"提示","密码不能为空.");
        return;
    }

    QSqlQuery query;
    query.exec("select pswd from tb_admin where account='"+account+"';");
    if(query.size() == 0){//如果在管理员表中没有找到该账号则在用户表中查找
        query.exec("select pswd from tb_student where id='"+account+"';");
        m_role = ROLE::STUDENT;
        if(query.size() == 0){//如果学生列表也没有找到该账号,就在教师列表里找
            query.exec("select pswd from tb_teacher where id='"+account+"';");
            m_role = ROLE::TEACHER;
            if(query.size() == 0){
                QMessageBox::warning(0,"警告","账号输入错误.");
                return;
            }

        }
    }

    query.first();
    if(query.isValid() && pswd != query.value("pswd").toString()){
        QMessageBox::warning(0,"警告","密码输入错误!");
        return;
    }



    if(m_role == ROLE::ADMIN){//管理员登陆
        if(ui->radioAdmin->isChecked() == false){
            QMessageBox::warning(0,"警告","登陆失败!");
            return;
        }
        this->close();//关闭登录器
        adminui* a = new adminui(&m_db,account);
        a->show();
    }else if(m_role == ROLE::STUDENT){//学生登陆
        if(ui->radioStudent->isChecked() == false){
            QMessageBox::warning(0,"警告","登陆失败!");
            return;
        }
        this->close();//关闭登录器
        studentui* s = new studentui(&m_db,account);
        s->show();
    }else if(m_role == ROLE::TEACHER){//教师登陆
        if(ui->radioTeacher->isChecked() == false){
            QMessageBox::warning(0,"警告","登陆失败!");
            return;
        }
        this->close();//关闭登录器s
        teacherui* t = new teacherui(&m_db,account);
        t->show();
    }


}

bool logui::ini()
{
    m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setDatabaseName("db_studentSys");
    m_db.setHostName("localhost");
    m_db.setUserName("root");
    m_db.setPassword("KWP-ffmxyr0");
    if(m_db.open() == true){
        return true;//打开数据库成功返回true
    }
    else{
        return false;
    }
}


void logui::on_btnCance_clicked()
{
    this->close();
}

